package com.android.lovely.ui.viewmodel

import androidx.lifecycle.viewModelScope
import com.android.lovely.api.service.userService
import com.android.lovely.data.SignResponse
import com.android.lovely.framework.BaseViewModel
import com.android.lovely.framework.launchWithLoading
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.withTimeoutOrNull

/**
 *
 * @author why
 * @date 2025/3/25 15:48
 */
class SignViewModel: BaseViewModel() {

    private val _signFlow = MutableSharedFlow<SignResponse>(extraBufferCapacity = 1)
    val signFlow: SharedFlow<SignResponse> get() = _signFlow

    fun requestDailySign() {
        viewModelScope.launchWithLoading {
            userService.getSignList().let {
                _signFlow.emit(it)
            }
        }
    }

    fun checkDailySign(type: Int, onSuccess: (Map<String, Int>?) -> Unit) {
        viewModelScope.launchWithLoading {
            var result: Map<String, Int>? = null
            withTimeoutOrNull(10_000) {
                awaitAll(async {
                    delay(1500L)
                }, async {
                    result = userService.checkInDaily(mapOf("ad_status" to type))
                })
            }
            onSuccess.invoke(result)
        }
    }
}